<?php

class FileSystemDao
{

    protected $_dbFile;
    protected $_table;
    protected $_db;

    # permission 

    public function __construct()
    {
        require_once("conf.php");
        $this->_dbFile = DemoConfig::$dbFile;
        $this->_db     = new SQLite3($this->_dbFile);
        $this->_table  = "tbl_file";
    }

    #
    public function listFiles($username, $permission)
    {
        $sql = sprintf("SELECT * FROM %s WHERE username = '%s' AND permission & %d", $this->_table, $username, $permission);
        #print $sql.PHP_EOL;
        $ret = $this->_query($sql);
        return $ret;
    }

    public function addFile($file, $filepath, $username, $permission)
    {
        $sql = sprintf("SELECT * FROM %s WHERE filename = '%s' AND filepath = '%s' AND username = '%s'", $this->_table, $file, $filepath, $username);
        
        $ret = $this->_query($sql);
        if (!empty($ret))
        {
            print "file already exists".PHP_EOL;
            return false;
        }

        $sql = sprintf("INSERT INTO %s (filename, filepath, created, username, permission) VALUES ('%s', '%s', '%s', '%s', %d)", $this->_table, $file, $filepath, date("Y-m-d H:i:s"), $username, $permission ); 

        $ret = $this->_db->exec($sql);
        return $ret;
    }
    
    
    public function delFile($filename, $filepath, $username, $permission)
    {
        $sql = sprintf("DELETE FROM %s WHERE filename = '%s' AND filepath= '%s' AND username = '%s'", $this->_table, $filename, $filepath, $username ); 
  
        #print $sql.PHP_EOL;
        $ret = $this->_db->exec($sql);
        return $ret;
    }
    
    public function setPermission($filename, $filepath, $username, $permission)
    {
        $sql = sprintf("UPDATE %s SET permission = %d WHERE filename = '%s' AND filepath= '%s' AND username = '%s'", $this->_table, $permission, $filename, $filepath, $username ); 
  
        #print $sql.PHP_EOL;
        $ret = $this->_db->exec($sql);
        return $ret;
    }

    private function _query($sql)
    {
        $results = $this->_db->query($sql);
        $ret = Array();
        while ($row = $results->fetchArray(SQLITE3_ASSOC))
        {
            $ret[] = $row;
        }
        return $ret;
    }
};

$debug = false;
if ($debug)
{

    $testdb = new DemoFileSystemDao();
    $user = "wei";
    $permission = 1;
    $res = $testdb->listFiles($user, $permission);
    var_export($res);

    $file = "testfile";
    $filePath = "/xx/bb/testfile";
    $user = 'wei';
    $permission = 2;
    $testdb->addFile($file, $filePath, $user, $permission);

    /*
    $file = "testfile";
    $filePath = "/xx/bb/testfile";
    $user = 'wei';
    $permission = 2;
    $testdb->delFile($file, $filePath, $user, $permission);
    $res = $testdb->listFiles($user, $permission);
    var_dump($res);

     */
    $permission = 4;
    $testdb->setPermission($file, $filePath, $user, $permission);
    $res = $testdb->listFiles($user, $permission);
    var_export($res);
}
